import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { map } from 'rxjs/operators';
import { ShipperBaseService } from '@shared';
import { InterfaceDockingService } from '../../services/interface-docking.service';
import { NzModalService } from 'ng-zorro-antd/modal';
import { VehicleConfirReceiptComponent } from '../../../order-management/modal/vehicle/confir-receipt/confir-receipt.component';
import { settingVehicleEditComponent } from '../set/edit.component';
import { confirReceiptComponent } from '../confir-receipt/confir-receipt.component';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-interface-docking-waybill',
  templateUrl: './waybill.component.html',
  styleUrls: ['./waybill.component.less']
})
export class interfaceDockingWaybillComponent implements OnInit {
  ui: SFUISchema = {};
  uiView: SFUISchema = {};
  schema: SFSchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  isVisible = false;
  _$expand = false;
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('stFloat') private readonly stFloat!: STComponent;
  @ViewChild('stFloatView') private readonly stFloatView!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  columns: STColumn[] = [];
  resourceStatus: any;
  tabs = {
    totalCount: 0,
    billStatus1: 0,
    billStatus2: 0,
    billStatus3: 0,
    billStatus4: 0,
    billStatus5: 0,
    billStatus6: 0,
    billStatus7: 0,
    billStatus8: 0,
    billStatus9: 0,
    billStatus10: 0,
    billStatus11: 0,
    billStatus12: 0,
    billStatus13: 0,
    billStatus14: 0
  };
  constructor(
    public service: InterfaceDockingService,
    public shipperservice: ShipperBaseService,
    private nzModalService: NzModalService,
    private router: Router,
    public route: ActivatedRoute,
    private ar: ActivatedRoute
  ) {}

  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus) {
      a.billStatus = this.resourceStatus;
    }
    console.log(this.sf?.value);

    const params: any = Object.assign({}, this.sf?.value || {});
    delete params._$expand;
    return {
      ...a,
      ...params,
      createTime: {
        start: this.sf?.value?.createTime?.[0] || '',
        end: this.sf?.value?.createTime?.[1] || ''
      },
      planDeliverTime: {
        start: this.sf?.value?.planDeliverTime?.[0] || '',
        end: this.sf?.value?.planDeliverTime?.[1] || ''
      },
      blLoadNo: this.sf?.value?.blLoadNo || ''
    };
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  search() {

    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  getGoodsSourceStatistical() {
    this.tabs = {
      totalCount: 0,
      billStatus1: 0,
      billStatus2: 0,
      billStatus3: 0,
      billStatus4: 0,
      billStatus5: 0,
      billStatus6: 0,
      billStatus7: 0,
      billStatus8: 0,
      billStatus9: 0,
      billStatus10: 0,
      billStatus11: 0,
      billStatus12: 0,
      billStatus13: 0,
      billStatus14: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.status;
    this.service.request(this.service.$api_listStatisticalStatus, params).subscribe((res: any) => {
      if (res) {
        let totalCount = 0;
        res.forEach((element: any) => {
          if (element.statusLabel === '新建') {
            this.tabs.billStatus1 = element.quantity;
          } else if (element.statusLabel === '已发布') {
            this.tabs.billStatus2 = element.quantity;
          } else if (element.statusLabel === '司机信息已获取') {
            this.tabs.billStatus3 = element.quantity;
          } else if (element.statusLabel === '已派车') {
            this.tabs.billStatus4 = element.quantity;
          } else if (element.statusLabel === '签收单号已接收') {
            this.tabs.billStatus5 = element.quantity;
          } else if (element.statusLabel === '签收单号已反馈') {
            this.tabs.billStatus6 = element.quantity;
          } else if (element.statusLabel === '报到已接收') {
            this.tabs.billStatus7 = element.quantity;
          } else if (element.statusLabel === '报到') {
            this.tabs.billStatus8 = element.quantity;
          } else if (element.statusLabel === '发运已接收') {
            this.tabs.billStatus9 = element.quantity;
          } else if (element.statusLabel === '发运') {
            this.tabs.billStatus10 = element.quantity;
          } else if (element.statusLabel === '到达已接收') {
            this.tabs.billStatus11 = element.quantity;
          } else if (element.statusLabel === '到达') {
            this.tabs.billStatus12 = element.quantity;
          } else if (element.statusLabel === 'POD已获取') {
            this.tabs.billStatus13 = element.quantity;
          } else if (element.statusLabel === '签收及回单上传') {
            this.tabs.billStatus14 = element.quantity;
          }
          totalCount += element.quantity;
        });
        this.tabs.totalCount = totalCount;
      }
    });
  }
  selectChange(e: number) {
    this.resourceStatus = e;
    switch (e) {
      case 0:
        this.resourceStatus = e;
        break;
      case 1:
        this.resourceStatus = 2;
        break;
      case 2:
        this.resourceStatus = 4;
        break;
      case 3:
        this.resourceStatus = 6;
        break;
      case 4:
        this.resourceStatus = 8;
        break;
      case 5:
        this.resourceStatus = 10;
        break;
      case 6:
        this.resourceStatus = 12;
        break;
      case 7:
        this.resourceStatus = 14;
        break;
    }
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  ngOnInit(): void {
    this.getGoodsSourceStatistical();
    this.initSF();
    this.initST();
    if (this.route.snapshot.queryParams.blLoadNo) {
      setTimeout(() => {
        if (this.sf) {
          this.sf.setValue('/blLoadNo', this.route.snapshot.queryParams.blLoadNo);
        }
        this.st.reload(this.reqParams);
      }, 0);
    }
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        blLoadNo: {
          type: 'string',
          title: '派车单号'
        },
        billCode: {
          type: 'string',
          title: '运单号'
        },
        blLoadNo2: {
          type: 'string',
          title: '签收单号'
        },
        status: {
          title: '运单状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'api:bill:status' },
            containsAllLabel: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        licenseNumber: {
          type: 'string',
          title: '车牌号',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        driverName: {
          type: 'string',
          title: '司机姓名',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        planDeliverTime: {
          title: '计划发货时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        }
      },
      type: 'object'
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }
  // 获取城市列表
  getRegionCode(regionCode: any) {
    console.log(regionCode);
    return this.service
      .request(this.service.$api_get_enterprise_project, { id: regionCode })
      .pipe(
        map(res =>
          res.map((item: any) => ({
            label: item.projectName,
            value: item.id
          }))
        )
      )
      .subscribe(res => {
        this.sf.getProperty('/enterpriseProjectId')!.schema.enum = res;
        this.sf.getProperty('/enterpriseProjectId')!.widget.reset(res);
      });
  }
  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '派车单号',
        width: '180px',
        fixed: 'left',
        className: 'text-left',
        render: 'blLoadNo',
        index: 'blLoadNo'
      },
      {
        title: '运单号',
        width: '180px',
        fixed: 'left',
        className: 'text-left',
        render: 'billCode',
        index: 'billCode'
      },
      {
        title: '车辆类型',
        width: '180px',
        className: 'text-left',
        index: 'vehicleType'
      },
      { title: '签收单号', index: 'blLoadNo2', width: '180px', className: 'text-left' },
      {
        title: '运单状态',
        width: '250px',
        className: 'text-left',
        index: 'statusLabel'
      },
      { title: '计划发货时间', index: 'planDeliverTime', width: '220px', className: 'text-left' },
      { title: '创建时间', index: 'createTime', width: '220px', className: 'text-left' },
      { title: '件数', index: 'quantity', width: '220px', className: 'text-left' },
      { title: '重量', index: 'weight', width: '180px', className: 'text-left' },
      { title: '体积', index: 'volume', width: '180px', className: 'text-left' },
      { title: '车牌号', index: 'licenseNumber', width: '180px', className: 'text-left' },
      { title: '司机姓名', index: 'driverName', width: '180px', className: 'text-left' },
      { title: '报到操作人', index: 'checkInName', width: '180px', className: 'text-left' },
      { title: '发运操作人', index: 'shipmentName', width: '180px', className: 'text-left' },
      { title: '到达操作人', index: 'arriveName', width: '180px', className: 'text-left' },
      {
        title: '操作',
        fixed: 'right',
        width: '120px',
        className: 'text-center block-td',
        buttons: [
          {
            text: `POD上传<br/>`,
            click: _record => this.confirmReceipt(_record)
          },
          {
            text: '查看详情',
            click: (item: any) => {
              this.router.navigate(['/interface-docking/bill-code-detail'], {queryParams: {blLoadNo :item.blLoadNo, billCode: item.billCode}});
            },
          }
        ]
      }
    ];
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  /**
   * 伸缩查询条件
   */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
  tabChange(item: any) {}
  /**
   * 重置表单
   */
  resetSF(): void {
    this.sf.reset();
    this._$expand = false;
  }

  /**
   * 修改司机信息
   */
  saveVehicleInfo() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择数据');
      return;
    }
    let judge = false;
    this.selectedRows.forEach(items => {
      if (items.status != 4) {
        judge = true;
      }
    });
    const modal = this.nzModalService.create({
      nzContent: settingVehicleEditComponent,
      nzWidth: 900,
      nzComponentParams: { params: { ...this.selectedRows } },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  confirmReceipt(value: any) {
    const modal = this.nzModalService.create({
      nzTitle: '确认签收',
      nzWidth: '50%',
      nzContent: confirReceiptComponent,
      nzComponentParams: {
        i: value
      },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  noticeCheckIn(operation: any) {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择数据');
      return;
    }
    let judge = false;
    this.selectedRows.forEach(items => {
      if (items.status != 4 && operation == '确认') {
        judge = true;
      } else if (items.status != 8 && operation == '取消') {
        judge = true;
      }
    });
    if (judge) {
      this.service.msgSrv.warning('当前状态不能点击' + operation + '报到操作');
      return;
    }
    this.nzModalService.confirm({
      nzTitle: '<i>报到' + operation + '</i>',
      nzContent: `是否` + operation + `报到？`,
      nzOnOk: () => {
        this.service.request(this.service.$api_noticeCheckIn + '?operation=' + operation, this.selectedRows).subscribe(res => {
          if (res) {
            this.service.msgSrv.success(operation + '报到成功');
            this.search();
          } else {
            this.service.msgSrv.error(operation + '报到失败');
          }
        });
      }
    });
  }

  noticeShipment(operation: any) {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择数据');
      return;
    }
    let judge = false;
    this.selectedRows.forEach(items => {
      if (items.status != 8 && operation == '确认') {
        judge = true;
      } else if (items.status != 10 && operation == '取消') {
        judge = true;
      } else if (items.blLoadNo2 == null || items.blLoadNo2 == '') {
        judge = true;
      }
    });
    if (judge) {
      this.service.msgSrv.warning('当前状态不能点击' + operation + '发运操作');
      return;
    }
    this.nzModalService.confirm({
      nzTitle: '<i>发运' + operation + '</i>',
      nzContent: `是否` + operation + `发运？`,
      nzOnOk: () => {
        this.service.request(this.service.$api_noticeShipment + '?operation=' + operation, this.selectedRows).subscribe(res => {
          if (res) {
            this.service.msgSrv.success(operation + '发运成功');
            this.search();
          } else {
            this.service.msgSrv.error(operation + '发运失败');
          }
        });
      }
    });
  }

  noticeArrive(operation: any) {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择数据');
      return;
    }
    let judge = false;
    this.selectedRows.forEach(items => {
      if (items.status != 10 && operation == '确认') {
        judge = true;
      } else if (items.status != 12 && operation == '取消') {
        judge = true;
      }
    });
    if (judge) {
      this.service.msgSrv.warning('当前状态不能点击' + operation + '到达操作');
      return;
    }
    this.nzModalService.confirm({
      nzTitle: '<i>到达' + operation + '</i>',
      nzContent: `是否` + operation + `到达？`,
      nzOnOk: () => {
        this.service.request(this.service.$api_noticeArrive + '?operation=' + operation, this.selectedRows).subscribe(res => {
          if (res) {
            this.service.msgSrv.success(operation + '到达成功');
            this.search();
          } else {
            this.service.msgSrv.error(operation + '到达失败');
          }
        });
      }
    });
  }

  exprot() {
    this.service.downloadFile(this.service.$api_get_asyncExport, { ...this.reqParams, pageSize: -1 });
  }
}
